import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:shop/main.dart';

import 'package:shop/modules/production_modules.dart';

class OverviewGoodsPage extends StatefulWidget {
  const OverviewGoodsPage({Key? key,required this.tracker}) : super(key: key);
  final Function tracker;
  @override
  State<OverviewGoodsPage> createState() => _OverviewGoodsPageState();
}

class _OverviewGoodsPageState extends State<OverviewGoodsPage> {
  List<Map> productData = [];
  final List _waterFallList = [];
  late ScrollController _controller;
  List<Map<String, dynamic>> goodsData = [
    {
      "product_id": "1",
      "product_name": "伊蕾娜",
      "product_price": "0",
      "product_coverimg": [
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13217788602%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652958334&t=96bba58648e744d339dcaf75d9610431"
      ],
      "product_intro":
          "那么,请回答,有着沉鱼落雁般的美貌,拥有一头灰色秀发,其美貌与其才能散发的光芒连太阳见了都不由眯起眼睛,不输给色彩斑斓的鲜花美得如花般绽放的屑之魔女是谁呢? "
    },
    {
      "product_id": "2",
      "product_name": "一条咸鱼",
      "product_price": "9.9",
      "product_coverimg": [
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fss2.meipian.me%2Fuser%2F2092221%2Fc74d004c00000001b8883080124119d9.jpg%3Fmeipian-raw%2Fbucket%2Fivwen%2Fkey%2FdXNlci8yMDkyMjIxL2M3NGQwMDRjMDAwMDAwMDFiODg4MzA4MDEyNDExOWQ5LmpwZw%3D%3D%2Fsign%2F5f5f6ea2f882177233bcb5d6b3b3507e.jpg&refer=http%3A%2F%2Fss2.meipian.me&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1661229481&t=7eb11754c396075af59d2d1b4049379d"
      ],
      "product_intro": "一条经年未见光明的咸鱼,女生自用,99新",
    },
  ];
  Widget waterCard(double item, int number) {
    return FutureBuilder(
        future: Product.productInfoInit().then((value) {
          for (int i = 0; i < value.length; i++) {
            productData.add(value[i]);
          }
        }),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          return Container(
            height: item,
            decoration: BoxDecoration(
                border: Border.all(color: Colors.yellow, width: 1),
                borderRadius: BorderRadius.circular(10)),
            child: MyCard(goodsData[number]),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    var randomNum = Random();
    _controller=ScrollController();
    //TODO 待重写
    for (var i = 0; i < 40; i++) {
      _waterFallList.add(180 + 150 * randomNum.nextDouble());
      //在此处设置card的最小长度（300），和随机的范围(0,150);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: InkWell(child:CircleAvatar(
          backgroundImage: NetworkImage('https://cdn.nlark.com/yuque/0/2022/jpeg/23159950/1664536788207-4ca31a99-e010-49c3-b50c-1f3feaf5c37e.jpeg'),
          ),
          onTap: (){widget.tracker(1);}
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        actions: [
        IconButton(icon:Icon(Icons.arrow_upward,color:Colors.black),
          onPressed: () {
            _controller.animateTo(0, duration: const Duration(milliseconds: 700), curve: Curves.ease);
          },),
          // IconButton(icon:Icon(Icons.search,color:Colors.black),
          // onPressed: (){
          //   Navigator.of(context).push(MaterialPageRoute(builder: (context){
          //     return Scaffold(
          //       appBar: AppBar(title:const Text("搜索页")),
          //       body: Center(
          //         child: Text("并没有搜索页",
          //           style: TextStyle(fontSize: 20),
          //         ),
          //       ),
          //     );
          //   }));
          // },),
      ].map((e) => IconButton(onPressed: (){}, icon: e)).toList(),
      ),
      body: SingleChildScrollView(
        controller: _controller,
        child: Container(
          padding: const EdgeInsets.all(10),
          child: MasonryGridView.count(

            // 展示几列
            crossAxisCount: 2,
            // 元素总个数
            itemCount: _waterFallList.length,
            // 单个子元素
            itemBuilder: (BuildContext context, int index) =>
                waterCard(_waterFallList[index], index % goodsData.length),
            // 纵向元素间距
            mainAxisSpacing: 10,
            // 横向元素间距
            crossAxisSpacing: 10,
            //本身不滚动，让外面的singlescrollview来滚动
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            //收缩，让元素宽度自适应
          ),
        ),
      ),
    );
  }
}

//卡片模板类

class MyCard extends StatefulWidget {
  final Map? pagemap;

  const MyCard(this.pagemap, {Key? key}) : super(key: key);

  @override
  State<MyCard> createState() => _MyCardState();
}

class _MyCardState extends State<MyCard> {
  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          //boxShadow: true,
          border: Border.all(color: Colors.white),
          borderRadius: BorderRadius.circular(20),
          color: Colors.green,
        ),
        child: ElevatedButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.white)),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return DetailGoodsPage(pagemap: widget.pagemap);
              }));
            },
            child: Column(children: <Widget>[
              Expanded(
                  flex: 2,
                  child: Container(
                    decoration: const BoxDecoration(
                      color: Colors.green,
                      //boxShadow: true,
                      borderRadius:
                          BorderRadius.vertical(top: Radius.circular(20)),
                    ),
                    //flex: 2,
                    //child: Container(
                    // color: Colors.white30,
                    child: Image.network(
                      widget.pagemap!["product_coverimg"][0],
                      fit: BoxFit.cover,
                    ),
                  )),
              Expanded(
                  flex: 1,
                  child: Row(children: <Widget>[
                    const Icon(Icons.add_photo_alternate_outlined),
                    Column(
                      children: <Widget>[
                        Text(
                          widget.pagemap!["product_name"],
                          style: const TextStyle(color: Colors.black,fontWeight: FontWeight.bold),
                        ),
                        Text(widget.pagemap!["product_price"],
                            style: const TextStyle(color: Colors.black54,fontStyle: FontStyle.italic))
                      ],
                    )
                  ]))
            ])));
  }
}
//文字背景
/* child: ListTile(
                    minVerticalPadding: 10,
                    leading: Icon(Icons.add_photo_alternate_outlined),
                    title: Text(
                      name,
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.clip,
                      style: const TextStyle(
                        fontSize: 20,
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                    subtitle: Text(
                      price,
                      style: const TextStyle(
                        fontSize: 30,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                ),
              )
            ],
          ),
        ))*/
